package formatter

import (
	"bytes"
	"gitee.com/go-boot/boot-interfaces/ilogger"
	"time"
)

type JsonFormatter struct {
}

func DefaultJsonFormatter() *JsonFormatter {
	return &JsonFormatter{}
}

// Format Json日志格式
func (j *JsonFormatter) Format(entry ilogger.IEntry) ([]byte, error) {
	var (
		timeData time.Time
		mapData  map[string]any
		buf      *bytes.Buffer
	)
	mapData, buf = entry.ToMap(), &bytes.Buffer{}
	timeData = mapData[ilogger.FieldKeyTime].(time.Time)
	buf.WriteByte('{')

	buf.WriteByte('"')
	buf.WriteString(ilogger.FieldKeyTime)
	buf.WriteByte('"')
	buf.WriteByte(':')
	buf.WriteByte('"')
	buf.WriteString(timeData.Format(ilogger.DefaultTimeFormat))
	buf.WriteByte('"')
	buf.WriteByte(',')

	buf.WriteByte('"')
	buf.WriteString(ilogger.FieldKeyLevel)
	buf.WriteByte('"')
	buf.WriteByte(':')
	buf.WriteByte('"')
	buf.WriteString(ilogger.LevelString(mapData[ilogger.FieldKeyLevel].(ilogger.LogLevel)))
	buf.WriteByte('"')
	buf.WriteByte(',')

	buf.WriteByte('"')
	buf.WriteString(ilogger.FieldKeyFile)
	buf.WriteByte('"')
	buf.WriteByte(':')
	buf.WriteByte('"')
	buf.WriteString(mapData[ilogger.FieldKeyFile].(string))
	buf.WriteByte('"')
	buf.WriteByte(',')

	buf.WriteByte('"')
	buf.WriteString(ilogger.FieldKeyMsg)
	buf.WriteByte('"')
	buf.WriteByte(':')
	buf.WriteByte('"')
	buf.WriteString(mapData[ilogger.FieldKeyMsg].(string))
	buf.WriteByte('"')
	buf.WriteByte('}')
	buf.WriteByte('\n')
	return buf.Bytes(), nil
}
